<template>
    <VZPanel title="售后分析缺陷模式分布" simple iconText="mdi-chart-pie">
      <div style="margin:-16px">
        <v-card>
          <v-row>
            <v-col cols="3">
              <v-autocomplete
                      v-model="selectedReferred"
                      :items="referredItems"
                      item-text="text"
                      item-value="id"
                      label="搜索零件简称"
                      outlined
                      dense
                      clearable
                      :filter="customFilter"
                      :loading="loading"
              ></v-autocomplete>
            </v-col>
            <v-col cols="3">
              <v-autocomplete
                      v-model="selectedMaterial"
                      :items="materialItems"
                      item-text="text"
                      item-value="id"
                      label="搜索产品"
                      outlined
                      dense
                      clearable
                      :filter="customFilter"
                      :loading="loading"
              ></v-autocomplete>
            </v-col>
            <v-col cols="2">
              <v-menu
                ref="startMenu"
                v-model="startMenu"
                :close-on-content-click="false"
                max-width="290"
                min-width="290"
                offset-y
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-text-field
                    v-model="startYear"
                    label="起始日期"
                    readonly
                    v-bind="attrs"
                    v-on="on"
                    outlined
                    dense
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="startYear"
                  type="month"
                  @change="startMenu = false"
                  :max="endYear"
                  locale="zh-cn"
                ></v-date-picker>
              </v-menu>
            </v-col>
            <v-col cols="2">
              <v-menu
                ref="endMenu"
                v-model="endMenu"
                :close-on-content-click="false"
                max-width="290"
                min-width="290"
                offset-y
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-text-field
                    v-model="endYear"
                    label="结束日期"
                    readonly
                    v-bind="attrs"
                    v-on="on"
                    outlined
                    dense
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="endYear"
                  type="month"
                  @change="endMenu = false"
                  :min="startYear"
                  locale="zh-cn"
                ></v-date-picker>
              </v-menu>
            </v-col>
            <v-col cols="1">
              <v-btn class="ma-1" outlined color="primary" @click="search_data" :disabled="loading"><v-icon>mdi-magnify</v-icon>查询</v-btn>
            </v-col>
          </v-row>
          <div ref="target" style="width:100%;height:400px"></div>
        </v-card>
      </div>
    </VZPanel>
  </template>
  
  <script>
    export default {
      data() {
        return {
          nameList: [],
          numList: [],
          materialSql: "SELECT id,name FROM tb_standard_assembly_product WHERE MARK_FOR_DELETE = 0",
          referredSql: "SELECT c.id,c.SIMPLE_CALL name FROM tt_sale_record_qms a  " +
                  "LEFT JOIN tb_standard_assembly_product b ON a.MATERIAL_ID = b.ID " +
                  "LEFT JOIN tb_standard_assembly_product_referred c ON c.id = b.REFERRED_ID " +
                  "WHERE c.SIMPLE_CALL IS NOT NULL  " +
                  "GROUP BY c.ID ",
          materialItems: [],
          referredItems: [],
          searchMaterial: '',
          selectedMaterial: '',
          selectedReferred: '',
          yearOptions: [], // 年份选项
          startYear: '',
          endYear: '',
          startMenu: false,
          endMenu: false,
          loading: true,
          materialIds: [], // 存储要查询的产品ID数组
        }
      },
      computed: {
        years() {
          if (!this.startYear || !this.endYear) return [];
          const start = parseInt(this.startYear);
          const end = parseInt(this.endYear);
          return Array.from({length: end - start + 1}, (_, i) => String(start + i));
        }
      },
      methods: {
        run() {
          if (!this.chartTarget) {
            this.chartTarget = this.$echarts.init(this.$refs.target);
          }
  
          // 先清空图表
          this.chartTarget.clear();
  
          // 计算累计值和百分比
          let total = this.numList.reduce((a, b) => a + b, 0);
          let percentList = this.numList.map(num => (num / total * 100).toFixed(1));
          let cumulative = [];
          let cumulativePercent = 0;
          this.numList.forEach(num => {
            cumulativePercent += (num / total * 100);
            cumulative.push(cumulativePercent.toFixed(1));
          });
  
          let option = {
            title: {
              text: '售后分析缺陷模式分布',
              left: 'center'
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross'
              },
              formatter: function(params) {
                let result = params[0].name + '<br/>';
                params.forEach(param => {
                  let marker = param.marker;
                  let value = param.value;
                  let seriesName = param.seriesName;
                  if (seriesName.includes('%')) {
                    value = value + '%';
                  }
                  result += marker + seriesName + ': ' + value + '<br/>';
                });
                return result;
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            legend: {
              data: ['数量', '占比', '累计占比']
            },
            xAxis: {
              type: 'category',
              data: this.nameList,
              axisLabel: {
                interval: 0,
                rotate: 45
              }
            },
            yAxis: [
              {
                type: 'value',
                name: '数量',
                position: 'left',
                axisLabel: {
                  formatter: '{value}'
                }
              },
              {
                type: 'value',
                name: '百分比',
                position: 'right',
                axisLabel: {
                  formatter: '{value}%'
                },
                max: 100
              }
            ],
            series: [
              {
                name: '数量',
                type: 'bar',
                data: this.numList,
                itemStyle: {
                  color: '#409EFF'
                },
                label: {
                  show: true,
                  position: 'top'
                }
              },
              {
                name: '占比',
                type: 'bar',
                data: percentList,
                itemStyle: {
                  color: '#E6A23C'
                },
                label: {
                  show: true,
                  position: 'top',
                  formatter: '{c}%'
                },
                yAxisIndex: 1
              },
              {
                name: '累计占比',
                type: 'line',
                data: cumulative,
                yAxisIndex: 1,
                itemStyle: {
                  color: '#67C23A'
                },
                label: {
                  show: true,
                  position: 'top',
                  formatter: '{c}%'
                }
              }
            ]
          };
          this.chartTarget.setOption(option);
        },
        search_data() {
          if (this.materialIds.length === 0) {
            return;
          }
          let _this = this;
          this.loading = true;
  
          let params = {
            "SQL": `SELECT b.FIRST_ANALYSE name, COUNT(1) num 
                    FROM tt_sale_record_qms a 
                    LEFT JOIN tt_mqp_defect b ON a.DEFECT_ID = b.id
                    WHERE a.MATERIAL_ID in (${this.materialIds.join(',')}) 
                    AND (DATE_FORMAT(a.MADE_TIME, '%Y-%m') >= '${this.startYear}'
                    AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') <= '${this.endYear}')
                    GROUP BY b.FIRST_ANALYSE
                    ORDER BY num DESC`
          };
  
          app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
            params: {
              functionParam: JSON.stringify(params)
            },
            callBack(res) {
              if (res.success) {
                _this.nameList = res.rows.map(item => item.name);
                _this.numList = res.rows.map(item => item.num);
                _this.run();
              }
              _this.loading = false;
            },
          });
        },
        // 获取零件简称信息
        loadReferredData() {
          let _this = this;
          _this.referredItems = [];
          let params = {"SQL": this.referredSql};
          app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
            params: {
              functionParam: JSON.stringify(params)
            },
            callBack(res) {
              if (res.success && res.rows.length > 0) {
                let dataList = res.rows;
                let referredList = [];
                dataList.forEach((item) => {
                  let map = {};
                  map.text = item.name;
                  map.id = item.id;
                  referredList.push(map);
                })
                _this.referredItems = referredList;
                // 设置默认选中第一个零件简称
                if (_this.referredItems.length > 0) {
                  _this.selectedReferred = _this.referredItems[0].id;
                  _this.loadMaterialIdsByReferred().then(() => {
                    if (_this.materialIds.length > 0) {
                      _this.search_data();
                    }
                  });
                }
              }
            },
          })
        },
        // 获取产品信息
        loadMaterialData() {
          let _this = this;
          _this.materialItems = [];
          let params = {"SQL": this.materialSql};
          app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
            params: {
              functionParam: JSON.stringify(params)
            },
            callBack(res) {
              if (res.success && res.rows.length > 0) {
                let dataList = res.rows;
                let materialList = [];
                dataList.forEach((item) => {
                  let map = {};
                  map.text = item.name;
                  map.id = item.id;
                  materialList.push(map);
                })
                _this.materialItems = materialList;
              }
              _this.loading = false;
            },
          })
        },
        // 根据零件简称获取产品ID列表
        loadMaterialIdsByReferred() {
          if (!this.selectedReferred) {
            this.materialIds = this.selectedMaterial ? [this.selectedMaterial] : [];
            return Promise.resolve();
          }
  
          let _this = this;
          let params = {
            "SQL": `SELECT DISTINCT a.id
                    FROM tb_standard_assembly_product a
                    WHERE a.MARK_FOR_DELETE = 0
                    AND a.REFERRED_ID = ${this.selectedReferred}`
          };
  
          return new Promise((resolve) => {
            app.utils.ajaxRequest({
              hideMsg: true,
              hideMask: true,
              url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
              params: {
                functionParam: JSON.stringify(params)
              },
              callBack(res) {
                if (res.success && res.rows.length > 0) {
                  _this.materialIds = res.rows.map(item => item.id);
                } else {
                  _this.materialIds = [];
                }
                resolve();
              },
            });
          });
        },
        // 初始化年份选项
        initYearOptions() {
          const currentDate = new Date();
          const currentYear = currentDate.getFullYear();
          const currentMonth = String(currentDate.getMonth() + 1).padStart(2, '0');
          
          // 设置默认值为当前年月
          this.endYear = `${currentYear}-${currentMonth}`;
          // 设置开始日期为3年前
          const startDate = new Date(currentDate);
          startDate.setFullYear(currentYear - 3);
          this.startYear = `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}`;
        },
        reset() {
          this.searchMaterial = '';
          this.selectedMaterial = '';
          this.selectedReferred = '';
          this.startYear = '';
          this.endYear = '';
          this.search_data();
        },
        customFilter(item, queryText, itemText) {
          const textOne = itemText.toLowerCase();
          const searchText = queryText.toLowerCase();
  
          return textOne.indexOf(searchText) > -1;
        },
      },
      watch: {
        selectedMaterial() {
          if (this.selectedMaterial) {
            // 如果选择了产品，清空简称选择
            this.selectedReferred = '';
            this.materialIds = [this.selectedMaterial];
            this.search_data();
          }
        },
        async selectedReferred() {
          if (this.selectedReferred) {
            // 如果选择了简称，清空产品选择
            this.selectedMaterial = '';
            // 等待获取产品ID列表完成
            await this.loadMaterialIdsByReferred();
            if (this.materialIds.length > 0) {
              this.search_data();
            }
          } else {
            // 如果清空了简称，且没有选择产品，清空materialIds
            if (!this.selectedMaterial) {
              this.materialIds = [];
            }
          }
        },
        startYear() {
          if (this.materialIds.length > 0) {
            this.search_data();
          }
        },
        endYear() {
          if (this.materialIds.length > 0) {
            this.search_data();
          }
        }
      },
      created() {
        this.initYearOptions();
        this.loadMaterialData();
        this.loadReferredData();
        setTimeout(() => {
          this.search_data();
        }, 1000);
      },
      mounted() {
        window.onresize = () => {
          this.chartTarget.resize();
        }
      },
    }
  </script>
  